package com.qidian.buy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidian.buy.mapper.ContentCategoryMapper;
import com.qidian.buy.pojo.ContentCategory;
import com.qidian.buy.service.ContentCategoryService;
import com.qidian.buy.util.QdConstant;
import com.qidian.buy.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2023/9/6 10:58
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
    @Autowired
    private ContentCategoryMapper categoryMapper;
    @Override
    public QdResult save(ContentCategory category) {
        // catMark不能重复
        QueryWrapper<ContentCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_mark",category.getCatMark());
        //wrapper.ne("status", QdConstant.DATA_DELETED);// 排除删除状态的数据
        ContentCategory contentCategory = categoryMapper.selectOne(wrapper);
        if(contentCategory != null){
            return QdResult.duplicate("内容类别的标记重复");
        }
        // 同一个父类别下，不能出现相同的名字
        wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",category.getParentId());
        wrapper.eq("cat_name",category.getCatName());
        wrapper.ne("status", QdConstant.DATA_DELETED);// 排除删除状态的数据
        contentCategory = categoryMapper.selectOne(wrapper);
        if(contentCategory != null){
            return QdResult.duplicate("内容类别的名字重复");
        }
        category.setCreateTime(new Date());
        category.setModifyTime(new Date());
        category.setStatus(1);
        return QdResult.isOk(categoryMapper.insert(category));
    }

    @Override
    public QdResult queryByParentId(Long parentId,int pageNum,int limit) {
        IPage<ContentCategory> page = new Page<>(pageNum,limit);
        QueryWrapper<ContentCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        wrapper.ne("status", QdConstant.DATA_DELETED);// 排除删除状态的数据
        page = categoryMapper.selectPage(page, wrapper);
        return QdResult.ok(page);
    }

    @Override
    public QdResult queryCountByParentId(Long parentId) {
        QueryWrapper<ContentCategory> wrapper = new QueryWrapper<>();
        wrapper.ne("status", QdConstant.DATA_DELETED);// 排除删除状态的数据
        wrapper.eq("parent_id",parentId);
        return QdResult.ok(categoryMapper.selectCount(wrapper) + "");
    }
}
